package com.taichuan.keysupport.view.panel;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.taichuan.keysupport.panel.PanelManager;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2019/12/19
 */
public abstract class TcPanelEditText extends EditText {
    private final String TAG = this.getClass().getSimpleName();

    protected PanelManager panelManager;

    public TcPanelEditText(Context context) {
        super(context);
    }

    public TcPanelEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TcPanelEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 定义一个方法用于根据设备是否为触摸屏设备 决定如何初始化EditText
     * @param context
     * @param isTouchDevice
     */
    public void init(Context context, boolean isTouchDevice) {
        Log.i(TAG, "init: 本页面初始化PanelEditText成功，本次PanelEditText启动时设备是否为触摸屏设备： " + isTouchDevice);
        if (!isTouchDevice){
            setOnFocusChangeListener(mFocusChangeListener);
            setOnKeyListener(setTcKeyListener());
            panelManager = initPanelManager(context);
        }
    }

    /**
     * 定义一个EditText的焦点变化监听器
     */
    private final OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                setSelection(getEditableText().length());
                if (panelManager != null) {
                    panelManager.showPopupWindow((EditText) v);
                }
            } else {
                if (panelManager != null)
                    panelManager.dissmissPopupWindow();
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (panelManager != null) {
            panelManager.close();
        }
    }

    /**
     * 定义一个抽象方法用于创建EditText的按键监听事件回调，具体实现交由子类完成
     * @return
     */
    protected abstract OnKeyListener setTcKeyListener();

    /**
     * 定义一个抽象方法用于创建EditText的键盘管理器，具体实现交由子类完成
     * @return
     */
    protected abstract PanelManager initPanelManager(Context context);
}
